"""
权限管理API端点
"""

from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional, List

from app.core.database import get_db
from app.core.dependencies import (
    get_current_active_user, require_permission_view, require_permission_manage,
    require_role_manage_with_permissions
)
from app.models.auth import User
from app.schemas.auth import (
    PermissionCreate, PermissionUpdate, PermissionResponse, PermissionListResponse
)
from app.schemas.common import BaseResponse
from app.services.permission_service import PermissionService
from app.utils.timezone_utils import get_shanghai_now
from app.core.logger import logger

router = APIRouter()
permission_service = PermissionService()


@router.post("", response_model=BaseResponse[PermissionResponse])
async def create_permission(
    permission_data: PermissionCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission_manage)
):
    """
    创建权限

    - **name**: 权限名称（唯一）
    - **display_name**: 权限显示名称
    - **description**: 权限描述（可选）
    - **resource**: 资源类型
    - **action**: 操作类型
    """
    try:
        result = await permission_service.create_permission(db, permission_data, current_user)

        return BaseResponse(
            data=result,
            message="权限创建成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建权限失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="创建权限失败"
        )


@router.get("", response_model=BaseResponse[PermissionListResponse])
async def get_permissions(
    resource: Optional[str] = Query(None, description="资源类型过滤"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_role_manage_with_permissions)
):
    """
    获取权限列表
    
    - **resource**: 按资源类型过滤
    """
    try:
        from sqlalchemy import select, and_
        from sqlalchemy.orm import selectinload
        from app.models.auth import Permission
        
        # 构建查询条件
        conditions = []
        
        if resource:
            conditions.append(Permission.resource == resource)
        
        # 查询权限列表
        stmt = select(Permission)
        
        if conditions:
            stmt = stmt.where(and_(*conditions))
        
        stmt = stmt.order_by(Permission.resource, Permission.action)
        
        result = await db.execute(stmt)
        permissions = result.scalars().all()
        
        return BaseResponse(
            data=PermissionListResponse(
                permissions=[PermissionResponse.from_orm(perm) for perm in permissions],
                total=len(permissions),
                page=1,
                page_size=len(permissions),
                total_pages=1
            ),
            message="获取权限列表成功",
            success=True
        )
    except Exception as e:
        logger.error(f"获取权限列表失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取权限列表失败"
        )


# 删除重复的路由定义 - 这个路由在后面有正确的实现


# 删除重复的create_permission路由 - 这个路由在开头有正确的实现


@router.put("/{permission_id}", response_model=BaseResponse[PermissionResponse])
async def update_permission(
    permission_id: int,
    permission_data: PermissionUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission_manage)
):
    """
    更新权限信息
    
    - **permission_id**: 权限ID
    - **display_name**: 权限显示名称（可选）
    - **description**: 权限描述（可选）
    """
    try:
        from sqlalchemy import select
        from app.models.auth import Permission
        from datetime import datetime
        
        # 查找权限
        stmt = select(Permission).where(Permission.id == permission_id)
        result = await db.execute(stmt)
        permission = result.scalar_one_or_none()
        
        if not permission:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="权限不存在"
            )
        
        # 检查是否为系统权限
        if permission.is_system and not current_user.is_superuser:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="无权修改系统权限"
            )
        
        # 更新权限信息
        update_data = permission_data.dict(exclude_unset=True)
        
        for field, value in update_data.items():
            setattr(permission, field, value)
        
        permission.updated_at = get_shanghai_now()
        await db.commit()
        
        logger.info(f"权限更新成功：{permission.name} (by {current_user.username})")
        
        return BaseResponse(
            data=PermissionResponse.from_orm(permission),
            message="权限更新成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新权限失败：{str(e)}")
        await db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="更新权限失败"
        )


@router.delete("/{permission_id}", response_model=BaseResponse[dict])
async def delete_permission(
    permission_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission_manage)
):
    """
    删除权限
    
    - **permission_id**: 权限ID
    """
    try:
        from sqlalchemy import select
        from app.models.auth import Permission, RolePermission
        
        # 查找权限
        stmt = select(Permission).where(Permission.id == permission_id)
        result = await db.execute(stmt)
        permission = result.scalar_one_or_none()
        
        if not permission:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="权限不存在"
            )
        
        # 检查是否为系统权限
        if permission.is_system:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="不能删除系统权限"
            )
        
        # 检查是否有角色使用此权限
        stmt = select(RolePermission).where(RolePermission.permission_id == permission_id)
        result = await db.execute(stmt)
        role_permissions = result.scalars().all()
        
        if role_permissions:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"权限正在被 {len(role_permissions)} 个角色使用，无法删除"
            )
        
        permission_name = permission.name
        await db.delete(permission)
        await db.commit()
        
        logger.info(f"权限删除成功：{permission_name} (by {current_user.username})")
        
        return BaseResponse(
            data={"message": f"权限 {permission_name} 删除成功"},
            message="权限删除成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除权限失败：{str(e)}")
        await db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除权限失败"
        )


@router.get("/resources", response_model=BaseResponse[List[str]])
async def get_resources(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_role_manage_with_permissions)
):
    """
    获取所有资源类型
    """
    try:
        result = await permission_service.get_resources(db)

        return BaseResponse(
            data=result,
            message="获取资源类型成功",
            success=True
        )
    except Exception as e:
        logger.error(f"获取资源类型失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取资源类型失败"
        )


@router.get("/resources/{resource}/actions", response_model=BaseResponse[List[str]])
async def get_resource_actions(
    resource: str,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_role_manage_with_permissions)
):
    """
    获取指定资源的所有操作类型
    """
    try:
        result = await permission_service.get_resource_actions(db, resource)

        return BaseResponse(
            data=result,
            message="获取资源操作成功",
            success=True
        )
    except Exception as e:
        logger.error(f"获取资源操作失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取资源操作失败"
        )


@router.get("/{permission_id}", response_model=BaseResponse[PermissionResponse])
async def get_permission(
    permission_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_role_manage_with_permissions)
):
    """获取权限详情"""
    try:
        result = await permission_service.get_permission(db, permission_id)

        return BaseResponse(
            data=result,
            message="获取权限详情成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取权限详情失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取权限详情失败"
        )


@router.put("/{permission_id}", response_model=BaseResponse[PermissionResponse])
async def update_permission(
    permission_id: int,
    permission_data: PermissionUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission_manage)
):
    """更新权限"""
    try:
        result = await permission_service.update_permission(db, permission_id, permission_data, current_user)

        return BaseResponse(
            data=result,
            message="权限更新成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新权限失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="更新权限失败"
        )


@router.delete("/{permission_id}", response_model=BaseResponse[dict])
async def delete_permission(
    permission_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission_manage)
):
    """删除权限"""
    try:
        await permission_service.delete_permission(db, permission_id, current_user)

        return BaseResponse(
            data={},
            message="权限删除成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除权限失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除权限失败"
        )


@router.post("/{permission_id}/assign", response_model=BaseResponse[dict])
async def assign_permission_to_roles(
    permission_id: int,
    request_data: dict,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(require_permission_manage)
):
    """分配权限给角色"""
    try:
        role_ids = request_data.get('role_ids', [])
        await permission_service.assign_permission_to_roles(db, permission_id, role_ids, current_user)

        return BaseResponse(
            data={},
            message="权限分配成功",
            success=True
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"权限分配失败：{str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="权限分配失败"
        )
